<template>
    <ClientDateRange @refresh="onConditionChange"></ClientDateRange>
    <el-table
        id="cntrleasereport-table-cntrleasereport"
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="cntr_corp_cod"
        :max-height="tableHeight"
        table-layout="auto"
        :summary-method="showSummaries"
        show-summary
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :formatter="col.formatter"
                :type="col.type"
                :fixed="col.fixed"
                :width="col.width"
            >
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-space>
            <NormalBtn @click="onQuery" :text="'生成租箱报表'"></NormalBtn>
            <el-dropdown @command="handleCommand">
                <el-button type="primary" class="btn">
                    导出 Excel<el-icon class="el-icon--right"
                        ><arrow-down
                    /></el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="current"
                            >当前页</el-dropdown-item
                        >
                        <el-dropdown-item command="all">全部</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-space>
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next, total"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <el-dialog
        v-model="dialogProsessVisible"
        title="导出"
        draggable
        destroy-on-close
        :center="true"
        width="90%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
    >
        <Progress :percent="paramData"> </Progress>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import ClientDateRange from '@/components/app/ClientDateRange.vue';
import dayjs, { Dayjs } from 'dayjs';
import { ClientAndDateRange } from '@/common/types/report';
import { ElMessage, TableColumnCtx, TableInstance } from 'element-plus';
import { Request } from '@/app/request';
import { LeaseReportModel } from '@/common/types/container';
import {
    tableColumnDefault,
    tableDefaultAttribute,
    useTableInfo,
} from '@/hooks/useTable';
import { tableMaxHeightAdjust } from '@/common/const';
import { TableColumn } from '@/common/types/app';
import { exportExcel, transFormatter } from '@/common/tools';
import { useAppStore } from '@/store/app';
import { storeToRefs } from 'pinia';
import { sum } from 'lodash';
const formData = ref<{ client_cod?: number; rangeDate: string }>({
    rangeDate: '',
});
const tableRef = ref<TableInstance>();
const tableData = ref<Array<LeaseReportModel>>([]);
const tableHeight = ref(600);
const { client } = storeToRefs(useAppStore());
const summary: Array<string> = [];
interface SummaryMethodProps<T = LeaseReportModel> {
    columns: TableColumnCtx<T extends LeaseReportModel ? LeaseReportModel : any>[];
    data: T[];
}
const dialogProsessVisible = ref(false);
const paramData = ref(0);
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'cntr_corp_cod') {
        data = client.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'cntr_corp_cod',
        label: '客户',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: client.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'total',
        label: '总租箱量',
        // fixed: 'left',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'back_total',
        label: '已退租箱量',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 4,
        prop: 'out_total',
        label: '在租箱量',
        width: 200,
    },
]);
const onConditionChange = (e: ClientAndDateRange) => {
    //console.log('onConditionChange', e);
    formData.value = e;
    // console.log(formData.value.client_cod);
};
onMounted(() => {
    tableHeight.value = window.innerHeight - tableMaxHeightAdjust - 70;
});
const getData = async () => {
    if (formData.value.rangeDate.length !== 2) {
        ElMessage.info('请选择时间段');
        return undefined;
    }
    // console.log(formData.value.rangeDate[1]);
    const param = {
        start_tim: formData.value.rangeDate[0],
        end_tim: dayjs(formData.value.rangeDate[1]).endOf('month').toDate(),
        fee_owner: formData.value.client_cod,
    };
    const req = new Request('生成租箱报表', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        ...param,
    });
    const r = await req.post();
    return r;
};
const onQuery = async () => {
    currentPage.value = 1;
    totalnum.value = 0;
    await onRefresh();
    // 动态调整表格字段
};
const onRefresh = async () => {
    const r = await getData();

    if (r && r.code > 100) {
        if (r.ext.total) {
            totalnum.value = parseInt(r.ext.rowCount);
        }
        if (r.ext) {
            summary.length = 0;
            summary[1] = '合计:';
            summary[2] = r.ext.total;
            summary[3] = r.ext.back_total;
            summary[4] = r.ext.out_total;
        }
        // totalnum.value = r.ext.total;
        tableData.value.length = 0;
        tableData.value = r.obj;
    }
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
const showSummaries = (param: SummaryMethodProps) => {
    if (Math.ceil(totalnum.value / pageSize.value) >= currentPage.value) {
        // console.log('合计',summary);
        
        return summary;
    } else {
        // console.log('合计','空');
        
        return [];
    }
};
const exportAll = async () => {
    if (totalnum.value <= 0) {
        ElMessage.info('请先生成报表数据');
        return;
    }
    
    const pages = Math.ceil(totalnum.value / pageSize.value);
    dialogProsessVisible.value = true;
    tableData.value.length = 0;
    for (let index = 1; index <= pages; index++) {
        currentPage.value = index;
        paramData.value = Math.round((index / pages) * 100);
        const r = await getData();
        if (r && r.code > 100) {
            tableData.value.push(...r.obj);
        }
    }
    await nextTick();
    exportExcel(`${tableRef.value!.$el.id}`);
    currentPage.value = 1;
    onRefresh();
    dialogProsessVisible.value = false;
};
const handleCommand = async (command: string | number | object) => {
    if (command === 'current') {
        exportExcel(`${tableRef.value!.$el.id}`);
    } else {
        await exportAll();
    }
};
</script>
<style lang="scss" scoped>
.query-filter {
    margin-bottom: 20px;
    padding: 10px;
    border: solid 2px var(--el-color-primary);
}
.query-filter .el-select {
    --el-select-width: 220px;
}
.query-filter .el-form-item {
    margin-bottom: 0px;
}
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}
.page {
    float: right;
    margin-top: 10px;
}
</style>
